package com.sky.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Slf4j
public class FileUploadUtils {

    /**
     * 将字节写入指定路径的文件中
     */
    public static void writeBytesToFile(byte[] bytes, String path, String filename) throws IOException {
        Path uploadPath = Paths.get(path);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath); // 自动创建目录
            log.info("已自动创建目录: {}", uploadPath);
        }

        try (FileOutputStream fos = new FileOutputStream(uploadPath.resolve(filename).toFile())) {
            fos.write(bytes);
            log.info("文件写入完成: {}/{}", path, filename);
        }
    }


    /**
     * 使用时间戳重命名文件
     */
    public static String getFileNameWithTimestamp(String originalFilename) {
        String prefix = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        String suffix = "";
        int dotIndex = originalFilename.lastIndexOf(".");
        if (dotIndex > 0) {
            suffix = originalFilename.substring(dotIndex);
        }
        return prefix + suffix;
    }
}

